// pages/calendar/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeDates: [],
    startTime: new Date(),
    endTime: new Date(),
    sep: "-",
    weeks: ['日', '一', '二', '三', '四', '五', '六'],
    months: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
    currentDay: 0,
    currentMonth: 0,
    currentYear: 0,
    currentWeek: 0,
    days: [],// 这个月的所有日期

    currentDateStr: '',   //选中的日期(默认今天)
    activeDateSet: new Set(),
    sameWeekIndex: -1, // 今日所在days 的索引值
    onlyThisWeekDays: [], // 当前周 的日期
    isFind: false,// 已经找到 周 数组
    isShowAllCalendar: false, // 展开收起日历
    taskDateList: [] // 任务日历集合
  },

  computedIsCanNext(){
    if (!this.data.endTime) {
      return true
    }
    if (this.data.endTime.getFullYear() > this.data.currentYear) {
      // 是否不在同一年 ，结束时间在 明年或者更后
      return true
    }
    else if (this.data.currentYear == this.data.endTime.getFullYear()) {
      // 是否 还有 活动日期在下个月
      return this.data.endTime.getMonth() > this.data.currentMonth
    }
    else {
      return true
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {


    this.render('2018', '01', '09');
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },
  //初始化
  initData: function (dateValue, sep) {
    var now = new Date();
    if (dateValue) {
      now = new Date(dateValue);
    }
    now = this.toUTC8(now)
    this.data.currentYear = now.getFullYear();
    this.data.currentMonth = now.getMonth(); //-1 month
    this.data.currentDay = now.getDate();
    this.data.currentDateStr = this.getDateStr(now, true);
  },
  toggleShowCalendar(){
    var isShowAllCalendar = !this.data.isShowAllCalendar
    this.setData({
      isShowAllCalendar: isShowAllCalendar
    })
  } , 

  //上一个月
  pickPre() {
    var currentMonth = this.data.currentMonth
    var currentYear = this.data.currentYear
    currentMonth -= 1
    if (currentMonth < 0) {
      currentMonth = 11
      currentYear -= 1
    }
    this.setData({
      isFind: false,
      currentMonth: currentMonth ,
      currentYear : currentYear ,
      currentDateStr :this.getDateStr(new Date(currentYear, currentMonth, this.data.currentDay), true)
    })
    this.render(currentYear, currentMonth, this.data.currentDay);
    //this.$emit("selectFunc", this.getDateStr(new Date(this.currentYear, this.currentMonth, this.currentDay), true));
  },
  //下一个月
  pickNext() {

    var currentMonth = this.data.currentMonth
    var currentYear = this.data.currentYear
    currentMonth += 1;
    if (currentMonth > 11) {
      currentMonth = 0;
      currentYear += 1;
    }
    this.setData({
      isFind: false,
      currentMonth: currentMonth,
      currentYear: currentYear,
      currentDateStr: this.getDateStr(new Date(currentYear, currentMonth, this.data.currentDay), true)
    })
    this.render(currentYear, currentMonth, this.data.currentDay);
    //this.$emit("selectFunc", this.getDateStr(new Date(this.currentYear, this.currentMonth, this.currentDay), true));
  },
  getDateStr(date, addZero) {
    if (!addZero) {
      return date.getFullYear() + this.data.sep + (date.getMonth() + 1) + this.data.sep + date.getDate();
    }
    return date.getFullYear() + this.data.sep + this.data.months[date.getMonth()] + this.data.sep + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
  },
  getDateStrLine(date, addZero) {
    if ( !addZero ) {
      return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
    }
    return date.getFullYear() + '-' + this.months[date.getMonth()] + '-' + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate())
  },

  //渲染
  render(year, month, day) {
    if (!this.data.startTime || !this.data.endTime) {
      return
    }
    var firstDateOfMonth = new Date(year, month, 1);    //这月第一天
    var lastDateOfMonth = new Date(year, month + 1, 0); //这月最后一天
    var monthLenght = lastDateOfMonth.getDate() - firstDateOfMonth.getDate() + 1;

    var toPreMonth = firstDateOfMonth.getDay(); //这个月的第一天是这周的第几天
    var toNextMonth = 6 - lastDateOfMonth.getDay(); //这个月的最后一天距离这周还剩几天
    var preMonthDays = [];  //上个月的日期
    var nextMonthDays = []; //下个月的日期
    var currentMonthDays = [];//这个月的日期
    for (let i = 0; i < toPreMonth; i++) {
      let tmp = new Date(year, month, -i);
      tmp.isNowMonth = false;             //不是当前月份
      tmp.dateStr = this.getDateStr(tmp, true); //加入日期标识字符，方便之后对比
      preMonthDays.unshift(tmp);
    }
    for (let i = 0; i < toNextMonth; i++) {
      let tmp = new Date(year, month + 1, i + 1);
      tmp.isNowMonth = false;             //不是当前月份
      tmp.dateStr = this.getDateStr(tmp, true); //加入日期标识字符，方便之后对比
      nextMonthDays.push(tmp);
    }
    for (let i = 0; i < monthLenght; i++) {
      let tmp = new Date(year, month, i + 1);
      tmp.isNowMonth = true;              //是当前月份
      tmp.dateStr = this.getDateStr(tmp, true); //加入日期标识字符，方便之后对比
      //判断这一天是否在活动范围之内
      var startTime = new Date()
      var endTime = new Date()
      //var startTime = this.data.startTime 
      //var endTime = this.data.endTime 
      console.log(endTime, startTime)

      endTime.setSeconds(0)
      endTime.setHours(0)
      endTime.setMilliseconds(0)
      startTime.setHours(0)
        startTime.setSeconds(0)
      startTime.setMilliseconds(0)
      
      this.setData({
        startTime: startTime ,
        endTime: endTime 
      
      })

      if ((this.data.startTime && this.data.endTime) && (+this.data.startTime) <= tmp.getTime() && this.data.endTime.getTime() >= tmp.getTime()) {
        tmp.isInRange = true;


        var current = this.data.getDateStrLine(tmp, true)

        if (this.data.taskDateList.indexOf(current) > -1) {
          tmp.activeClassName = 'active'
          let beforeDateStr = this.data.getDateStrLine(new Date(tmp.getFullYear(), tmp.getMonth(), tmp.getDate() - 1), true);
          let afterDateStr = this.data.getDateStrLine(new Date(tmp.getFullYear(), tmp.getMonth(), tmp.getDate() + 1), true);

          if (this.data.taskDateList.indexOf(beforeDateStr) > -1) {
            tmp.hasLeft = true;
          }
          if (this.data.taskDateList.indexOf(afterDateStr) > -1) {
            tmp.hasRight = true;
          }

        }


        //判断这一天是否有打卡
        /*  if (this.activeDateSet.has(tmp.dateStr)) {
            tmp.activeClassName = 'active'
            let beforeDateStr = this.getDateStr(new Date(tmp.getFullYear(), tmp.getMonth(), tmp.getDate() - 1),true);
            let afterDateStr = this.getDateStr(new Date(tmp.getFullYear(), tmp.getMonth(), tmp.getDate() + 1),true);
            if (this.activeDateSet.has(beforeDateStr)) {
              tmp.hasLeft = true;
            }
            if (this.activeDateSet.has(afterDateStr)) {
              tmp.hasRight = true;
            }
          }*/



      } else {
        tmp.isInRange = false;
      }
      //if(isSameWeek){
      //  /* 用于辅助（收起日历时） 判断 是否 同一周*/
      //  tmp.isSameWeek = true
      //}
      currentMonthDays.push(tmp);
    }
    this.setData({
      days: preMonthDays.concat(currentMonthDays, nextMonthDays)
    })
    //this.days = preMonthDays.concat(currentMonthDays, nextMonthDays);
    this.data.days.forEach((val, key) => {

      if ((new Date()).getDate() == val.getDate() && new Date().getMonth() == val.getMonth()) {
        this.setData({
          sameWeekIndex : key  
        })
        //this.sameWeekIndex = key
      }
    })
    // 以7天进行分割
    var com = [0, 7, 14, 21, 28, 35]
    var isFind = false
    if (this.data.isFind) {
      return
    }
    // 根据 当天的索引 查出 同一周的 days （收起时显示）
    com.forEach((val, key) => {
      if (this.data.sameWeekIndex >= val && this.data.sameWeekIndex <= com[key + 1] && !this.data.isFind) {
        this.setData({
          isFind: true
        })
        //this.isFind = true
        var _days = []


        var max = com[key + 1]
        for (let i = val; i < max; i++) {
          _days.push(this.data.days[i])

        }
        this.setData({
          onlyThisWeekDays : _days
        })
        //this.onlyThisWeekDays = _days
      }
    })
  },
  //选择日期
  pickDate(date) {
    this.currentDateStr = this.getDateStr(date, true);
    this.currentYear = date.getFullYear();
    this.currentMonth = date.getMonth(); //-1 month
    this.currentDay = date.getDate();
    //this.$emit("selectFunc", this.getDateStr(date, true))
  },
  pickDateNotInRange(date) {
    this.currentDateStr = this.getDateStr(date, true)
    this.currentYear = date.getFullYear()
    this.currentMonth = date.getMonth() //-1 month
    this.currentDay = date.getDate()
    // 这样页面不加载 momentList
    //this.$emit("selectFunc", this.getDateStr(date, true))
  },
  //上一个月
  pickPre() {
    this.isFind = false
    this.currentMonth -= 1;
    if (this.currentMonth < 0) {
      this.currentMonth = 11;
      this.currentYear -= 1;
    }
    this.currentDateStr = this.getDateStr(new Date(this.currentYear, this.currentMonth, this.currentDay), true);
    this.render(this.currentYear, this.currentMonth, this.currentDay);
    // this.$emit("selectFunc", this.getDateStr(new Date(this.currentYear, this.currentMonth, this.currentDay), true));
  },
  //下一个月
  pickNext() {
    this.isFind = false
    this.currentMonth += 1;
    if (this.currentMonth > 11) {
      this.currentMonth = 0;
      this.currentYear += 1;
    }
    this.currentDateStr = this.getDateStr(new Date(this.currentYear, this.currentMonth, this.currentDay), true);
    this.render(this.currentYear, this.currentMonth, this.currentDay);
    this.$emit("selectFunc", this.getDateStr(new Date(this.currentYear, this.currentMonth, this.currentDay), true));
  },

  whenStartTimeChange(){
    task.getDailyTaskCalendar({
      activityId: this.$route.query.id
    })
    .then(res => {

      if (this.activeDates.length > 0) {
        for (let d of this.activeDates) {
          this.activeDateSet.add(d);
        }
        this.render(this.currentYear, this.currentMonth, this.currentDay);
      }

      if (res.status == 0) {
        this.setData({
          taskDateList: res.data.dateList ,
        })
        //this.taskDateList = res.data.dateList
        var len = this.taskDateList.length
        // this.$emit('showTaskMask', len)
        //this.taskDateList = ['2017-10-26','2017-10-27','2017-10-28','2017-10-30','2017-10-31','2017-11-01']
        this.render(this.currentYear, this.currentMonth, this.currentDay)
      }
      else {
        this.util.msg.error(res.msg)
      }
    })
  },

  /*转换时区*/
  toUTC8(date) {
    if (date.getTimezoneOffset && date.getTimezoneOffset() != 480) {
      var offset = date.getTimezoneOffset()
      if (offset > 0) {
        date = new Date(date.getTime() + (offset + 480) * 60 * 1000)
      }
      if (offset <= 0) {
        date = new Date(date.getTime() + (480 + offset) * 60 * 1000)
      }
      date.setHours(0)
      date.setMinutes(0)
      return date
    } else {
      return date
    }
  },
  /*
   * @parames 时间对象
   * 是否同一周
   */
  isSameWeek(old, now) {
    var oneDayTime = 1000 * 60 * 60 * 24
    var old_count = parseInt(+old / oneDayTime)
    var now_other = parseInt(+now / oneDayTime)
    return parseInt((old_count + 4) / 7) == parseInt((now_other + 4) / 7);
  }
})
